package com.mathlearning.auth.repository;

import com.mathlearning.auth.entity.Conversation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface ConversationRepository extends JpaRepository<Conversation, Long> {
    
    /**
     * 查找会话（确保userAId < userBId）
     */
    Optional<Conversation> findByUserAIdAndUserBId(Long userAId, Long userBId);
    
    /**
     * 查询用户的所有会话
     */
    @Query("SELECT c FROM Conversation c WHERE c.userAId = :userId OR c.userBId = :userId ORDER BY c.lastMessageTime DESC")
    Page<Conversation> findUserConversations(@Param("userId") Long userId, Pageable pageable);
    
    /**
     * 删除会话
     */
    @Query("DELETE FROM Conversation c WHERE (c.userAId = :userId1 AND c.userBId = :userId2) OR (c.userAId = :userId2 AND c.userBId = :userId1)")
    void deleteConversationBetweenUsers(@Param("userId1") Long userId1, @Param("userId2") Long userId2);
}








